package org.csu.jpetstore_users_backend_pj.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.csu.jpetstore_users_backend_pj.config.AliyunConfig;
import org.csu.jpetstore_users_backend_pj.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service("aliyunSmsService")
public class AliyunSmsServiceImpl implements SmsService {
    @Autowired
    private AliyunConfig aliyunConfig;

    @Override
    public boolean sendSms(String phoneNumber, String code) throws Exception {
        String accessKeyId = aliyunConfig.getAccessKeyId();
        String accessKeySecret = aliyunConfig.getAccessKeySecret();
        String signName = "mypet商店";
        String templateCode = aliyunConfig.getTemplateCode();

            Config config = new Config()
                    .setAccessKeyId(accessKeyId)
                    .setAccessKeySecret(accessKeySecret);
            config.endpoint = "dysmsapi.aliyuncs.com";

            Client client = new Client(config);
            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam(JSON.toJSONString(Collections.singletonMap("code", code)));

            SendSmsResponse response = client.sendSms(request);
            return "OK".equalsIgnoreCase(response.getBody().getCode());
    }
    public static void main(String[] args) throws Exception {
        // 创建 SmsService 实例

        SmsService smsService = null; // 实际会注入AliyunSmsServiceImpl
        
        // 测试的手机号码
        String phone = "15274840858";
        boolean sendResult = smsService.sendSms(phone, "111111");
    }
}